home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: Floating point calculation order
- Date: 23 Jan 96 20:02:13 GMT
- Organization: Clemson University
- Message-ID: <mjs.822427333@hubcap>
- References: <m0tedv8-0002eqC@sice.nsk.su> <3104c6d9.134061184@nntp.ix.netcom.com> <DLnE5K.2xH@microunity.com>
- NNTP-Posting-Host: hubcap.clemson.edu
-
- toms@MicroUnity.com (Tom Sanders) writes:
- %In article <3104c6d9.134061184@nntp.ix.netcom.com>, miker3@ix.netcom.com (Mike Rubenstein) writes:
- %|> "Pavel A. Zemtsov" <PZEM@sice.nsk.su> wrote:
- %|> > Having declaration
- %|> >
- %|> > double x, p, q, r;
- %|> >
- %|> > my compiler (cc on SCO 3.2) calculated following expression:
- %|> >
- %|> > x = p * q / r;
- %|> >
- %|> > as p * (q/r); (I mean, it divided first, than multiplied). That
- %|> > resulted in precision loss.
- %|> >
- %|> > Is this legal behavior?
- %|>
- %|> Not in ANSI C, but it was legal in K&R. If memory serves, it was not
- %|> made illegal until very late in the standardizattion process so if
- %|> your compiler was written before the standard was finalized it may not
- %|> adhere to this.
-
- %I am a firm believer in not allowing a compiler to make these decisions for
- %me. It's best to specify with parens the order of evaluation and not leave
- %it up to the compiler defaults. I would actually prefer a compiler that
- %gave a warning if I did have an equation that could be evaluated in more
- %than 1 order (something I have not done in over 20 years).
-
- As I understand it, before ANSI, the compiler was free to even ignore
- parentheses and reorder the evaluation as long as the result was
- *mathematically* equivalent to the original expression. So the only
- way to force an evaluation order was to use multi-line code with
- temporaries to hold the intermediate results.
-
- Would somebody explain under exactly what circumstances an ANSI
- compiler is and is not allowed to reorder evaluation? My recollection
- was that parentheses forced evaluation order, but leaving them off
- allowed the compiler the freedom to reorder. That's not what
- Rubenstein is claiming, though.
-
- Thus, in
-
- x = p * q / r;
-
- the compiler is legally allowed to do the division first, but in
-
- x = (p * q) / r;
-
- it is not, so that Sanders's strategy is effective in this case.
-
- I also recall that the unary + was supposed to be useful in enforcing
- evaluation order, but I can't recall how it fits in.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-